<template>
    <view class="page">
        <cu-custom bgColor="bg-gradual-green" :isBack="true">
            <block slot="content">编辑问题</block>
            <block slot="backText">返回</block>
        </cu-custom>
        <view class="uni-picker-wrapper">
            <view class="cu-form-group">
                <view class="cu-bar bg-white">
                    <view class="action">
                        <text class="cuIcon-titles text-green"></text> 课程名称
                    </view>
                </view>
                <picker @change="courseChange" :value="courseID" :range="courses">
                    <view class="picker" style="font-size: 30rpx;">
                        {{courseID>-1?courses[courseID]:'请选择课程名称'}}
                    </view>
                </picker>
            </view>
        </view>
        <view class="uni-picker-wrapper">
            <view class="cu-form-group">
                <view class="cu-bar bg-white">
                    <view class="action">
                        <text class="cuIcon-titles text-green"></text> 章节名称
                    </view>
                </view>
                <picker :disabled="courseID<=-1" @change="chapterChange" :value="chapterID" :range="chapters">
                    <view class="picker" style="font-size: 30rpx;">
                        {{chapterID>-1?chapters[chapterID]:'请选择章节名称'}}
                    </view>
                </picker>
            </view>
        </view>
        <view class="post-title-wrapper">
            <view class="uni-input-wrapper">
                <view class="cu-bar bg-white" style="margin-left: 28rpx;">
                    <view class="action">
                        <text class="cuIcon-titles text-green"></text> 标题
                    </view>
                </view>
                <button class="post-btn bg-green text-xl shadow" v-show="!startTitleAudio" @click="startTitle()">
                    <text class="cuIcon-voice"></text>
                </button>
                <text class="lg text-green cuIcon-squarecheckfill" style="font-size: 60rpx;" v-show="startTitleAudio" @click="endTitle()"></text>
            </view>
            <view class="uni-input-title-wrapper">
                <input class="uni-input margin-lr-sm" v-model="inputTitle" placeholder="请输入问题标题" @input="onInputTitle" />
            </view>
        </view>
        <view class="post-content-wrapper">
            <view class="uni-input-wrapper">
                <view class="cu-bar bg-white" style="margin-left: 28rpx;">
                    <view class="action">
                        <text class="cuIcon-titles text-green"></text> 内容
                    </view>
                </view>
                <button class="post-btn bg-green text-xl shadow" v-show="!startContentAudio" @click="startContent()">
                    <text class="cuIcon-voice"></text>
                </button>
                <text class="lg text-green cuIcon-squarecheckfill" style="font-size: 60rpx;" v-show="startContentAudio" @click="endContent()"></text>
            </view>
            <view class="uni-input-content-wrapper margin-bottom-sm">
                <textarea class="uni-input margin-lr-sm" :maxlength="-1" v-model="inputContent" placeholder="请输入问题内容" @input="onInputContent" />
            </view>
        </view>
        <view class="cu-form-group" :key="columns">
            <view class="grid col-3 grid-square flex-sub">
                <view class="bg-img" v-for="(image,index) in images" :key="index">
                    <image :src="image" mode="aspectFill"></image>
                    <view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
                        <text class='lg text-green cuIcon-close'></text>
                    </view>
                </view>
                <view class="solids" @click="ImageMethod">
                    <text class='cuIcon-cameraadd'></text>
                </view>
            </view>
        </view>
        <view class="uni-button-wrapper" style="position: relative;">
            <view class="margin-tb-sm flex justify-center">
                <button :disabled="enableSend()" class="cu-btn round bg-green block shadow" @click="submit()">发表</button>
            </view>
            <view class="margin-tb-sm flex justify-center">
                <button class="cu-btn round lines-olive block shadow" @click="withDraw()">取消</button>
            </view>
        </view>
        <view>
            <pop-method :show="showImageMethod" @imageready="receiveImage" @closeme="closeImageMethod"></pop-method>
        </view>
    </view>
</template>

<script>
import popMethod from './pop-method/pop-method.vue';

export default {
    name: 'createQuestion',
    components: {
        popMethod
    },
    data() {
        return {
            currentCameraSrc: '',
            inputTitle: '',
            inputContent: '',
            images: [],
            currentVoiceSrc: ['content', 'title'],
            startTitleAudio: false,
            startContentAudio: false,
            voicePath: '',
            playAudio: false,
            showImageMethod: false,
            courses: [],	//选择框————课程
            chapters: [],   //选择框——章节
            DBData: [],	    //缓冲区的总数据
            courseID: -1,
            chapterID: -1,
            course_id: 1024,
            chapter_id: 1024,
            manager: null
        };
    },
    onShow() {
        var token = getApp().globalData.user.token;
        if(!token || token == '')
            return;
        this.init();
    },
    onLoad() {
        let self = this;
        var plugin = requirePlugin('WechatSI');
        self.manager = plugin.getRecordRecognitionManager();
        self.manager.onStop = function(res) {
            uni.hideLoading();
            if(self.currentVoiceSrc === 'title')
            {
                self.inputTitle = res.result;
            }
            else
            {
                if(self.currentVoiceSrc !== 'content')return;
                self.inputContent = res.result;
            }
        };
    },
    methods: {
        async init() {
            let self = this;

            uni.getStorage({
                key: 'CourseWithChapter',
                success: (res) => {
                    self.DBData = res.data;
                    for(var COURSE of res.data)
                        self.courses.push(COURSE.course.name);
                },
                fail: ()  => {
                    console.log('createQuestion getStore fail');
                }
            });
        },
        courseChange(e) {
            if(!this.DBData || this.DBData.length === 0)return;
            this.chapters = [];
            this.courseID = e.detail.value;
            if(this.courseID < 0 )return;
            this.course_id = this.DBData[this.courseID].course.id;
            let rawChapters = this.DBData[this.courseID].chapters;
            for(var chapter of rawChapters)
            {
                this.chapters.push(chapter.chapter_title);
            }
            // Update related chapters selected
            this.chapterID = -1;
        },
        chapterChange(e) {
            if(!this.chapters || this.chapters.length === 0)return;
            this.chapterID = e.detail.value;
            if(this.chapterID < 0)return;
            let rawChapters = this.DBData[this.courseID].chapters;
            var chapter_name = this.chapters[this.chapterID];
            let item = rawChapters.find(function(x) {
                return x.chapter_title === chapter_name;
            });
            if(item === undefined)
                this.chapter_id = 0;
            else
                this.chapter_id = item.course_chapter_id;
        },
        submit() {
            var sendMessage = {
                'content': {'text': this.inputContent, 'images': this.images},
                'title': this.inputTitle,
                'course_id': this.course_id,
                'chapter_id': this.chapter_id,
                'anonymity': 1
            };
            uni.$emit('create-question', sendMessage);
            uni.switchTab({
                url: '/pages/tutor/tutor',
                success: function() {
                },
                fail: function() {
                }
            });
        },
        startTitle() {
            if(this.startContentAudio)return;
            this.currentVoiceSrc = 'title';
            this.startTitleAudio = true;
            if(!this.manager)
                return;
            this.manager.start({duration: 60000, lang: 'zh_CN'});
        },
        endTitle() {
            this.startTitleAudio = false;
            this.manager.stop();
            uni.showLoading({
                title: '语音识别中'
            });
        },
        startContent() {
            if(this.startTitleAudio) return;
            this.currentVoiceSrc = 'content';
            this.startContentAudio = true;
            if(!this.manager)
                return;
            this.manager.start({duration: 60000, lang: 'zh_CN'});
        },
        endContent() {
            this.startContentAudio = false;
            this.manager.stop();
            uni.showLoading({
                title: '语音识别中'
            });
        },
        onInputTitle(e) {
            this.inputTitle = e.detail.value;
        },
        onInputContent(e) {
            this.inputContent = e.detail.value;
        },
        ImageMethod() {
            this.showImageMethod = true;
        },
        closeImageMethod(e) {
            if(e.show === false)
                this.showImageMethod = false;
        },
        receiveImage(e) {
            var received = e.images;
            if(received)
            {
                this.images = this.images.concat(received);
            }
        },
        DelImg(e) {
            uni.showModal({
                title: '删除',
                content: '确定要删除这张照片吗？',
                cancelText: '取消',
                confirmText: '删除',
                success: res => {
                    if (res.confirm) {
                        this.images.splice(e.currentTarget.dataset.index, 1);
                    }
                }
            });
        },
        withDraw() {
            uni.navigateBack();
        },
        enableSend() {
            var res = this.images.length === 0 && (this.inputTitle.length === 0 || this.inputContent.length === 0) || this.courseID === -1 || this.chapterID === -1;
            return res;
        }
    }
};
</script>

<style lang="scss" scoped>
    $btnSize: 60rpx;
    $input-height: 10em;

    .page{
        height: 100%;
        width: 100%;
        background-color: white;
    }
    .post-btn {
        width: $btnSize;
        height: $btnSize;
        position: relative;
        display: inline-flex;
        border-radius: 50%;
        z-index: 100;
        justify-content: center;
        align-items: center;
        margin-left: 0;
    }

    .uni-input-wrapper{
        display: flex;
        background-color: #FFFFFF;
        position: relative;
        overflow: hidden;
        flex-direction: row;
        flex-wrap: wrap;
        align-items: center;
        justify-items: center;
        justify-content: flex-start;
        .cu-bar{
            .action{
                font-size: 34upx;
                font-weight: bold;
            }
        }
    }

    .uni-picker-wrapper{
        display: flex;
        background-color: #FFFFFF;
        position: relative;
        overflow: hidden;
        flex-direction: column;
        flex-wrap: wrap;
        justify-content: flex-start;
        .cu-bar{
            .action{
                font-size: 34upx;
                font-weight: bold;
            }
        }
    }

    .uni-input-title-wrapper {
        background-color: #FFFFFF;
        position: relative;
        overflow: hidden;
        min-height: 80rpx;
        input{
            height: 64rpx;
            border-radius: 10rpx;
            padding: 0 20rpx;
            background-color: rgb(250, 250, 250);
        }
    }

    .uni-input-content-wrapper {
        background-color: #FFFFFF;
        position: relative;
        overflow: hidden;
        textarea{
            background-color: rgb(250, 250, 250);
            height: $input-height;
            padding: 20rpx;
        }
    }

    /** 必须提升样式优先权(!important) **/
    button[disabled] {
      color: white !important;
      background: #79c242 !important;
    }

    .uni-input {
        width: auto;
        font-size: 30rpx;
        font-family: 'Courier New', Courier, monospace;
    }


    .post-content-wrapper{
        background-color: #FFFFFF;
        position: relative;
        overflow: hidden;
    }

    .uni-button-wrapper{
        overflow: hidden;
        margin-top: 50rpx;
        background-color: $uni-bg-color;
        width: 100%;
        bottom: 0;
    }

    .cu-btn.block{
        width: 60%;
    }

    .cu-form-group .title {
        min-width: calc(4em + 15px);
    }
</style>
